package controllers

import (
	"errors"
	"github.com/gin-gonic/gin"
	"net/http"
)

// BaseController
// @Description: 控制器继承
type BaseController struct {
}

// Success
//
//	@Description: 成功
//	@receiver base
//	@param c
//	@param data
func (base BaseController) Success(c *gin.Context, data any) {
	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "操作成功",
		"data":    data,
		"success": true,
	})
}

// Error
//
//	@Description: 失败
//	@receiver base
//	@param c
func (base BaseController) Error(c *gin.Context, msg string) {
	//处理异常
	defer handleError(c)

	//模拟异常
	err := errors.New("操作失败")
	if err != nil {
		panic(err)
	}
	c.JSON(http.StatusOK, gin.H{
		"code":    500,
		"message": msg,
		"data":    nil,
		"success": false,
	})

}

func handleError(c *gin.Context) {
	if err := recover(); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    500,
			"message": "服务器异常",
			"data":    nil,
			"success": false,
		})
	}
}
